package com.example.tests;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;


import com.example.fw.ContactHelper.*;

import com.example.utils.SortedListOf;
import com.thoughtworks.xstream.XStream;
import com.example.fw.ContactHelper.*;


public class ContactDataGenerator extends AddressbookTestBase{

/*	public ContactDataGenerator(ApplicationManager appManager) {
		super(appManager);
	}*/

	public void main(String[] args) throws IOException{
		if(args.length < 3){
			System.out.println("Please specify parameters: <tests amount> <file destination> <file format>");
			return;
		}

		int amount = Integer.parseInt(args[0]);
		File file = new File(args[1]);
		String format = args[2];
		
		if(file.exists()){
			System.out.println("File " + file + " is already exists,pls. remove it manually.");
			return;	
		}
		
		List<ContactData> contacts = generateRandomContacts(amount);
		if(format.equals("csv")){
			saveContactsToCsvFile(contacts, file);
		} else if(format.equals("xml")){
			saveContactsToXmlFile(contacts, file);			
		} else {
			System.out.println("Unknown format " + format);
			return;
		} 		
	}

	public List<ContactData> generateRandomContacts(int amount) {
		List<ContactData> list = new ArrayList<ContactData>();	
		for (int i = 0; i < amount; i++) {
			ContactData contactInput = new ContactData()
				.withFirstName(generateRandomString())
				.withLastName(generateRandomString())
				.withFirstAddress(generateRandomString())
				.withHomePhone(generateRandomString())
				.withMobilePhone(generateRandomString())
				.withWorkPhone(generateRandomString())
				.withFirstEmail(generateRandomString())
				.withSecondEmail(generateRandomString())
				.withBDay(generateRandomDay())
				.withBMonth(generateRandomMonth())
				.withBYear(generateRandomYear())
				.withGroupLink("[none]")
				//contactInput.groupLinkage = "[none]";
				.withSecondAddress(generateRandomString())
				.withSecondPhone(generateRandomString());
		list.add(contactInput);
		}
		return list;		
	}
	
	private static void saveContactsToXmlFile(List<ContactData> contacts, File file) throws IOException {
		XStream xstream = new XStream();
		xstream.alias("contacts", ContactData.class);
		String xml = xstream.toXML(contacts);
		FileWriter writer = new FileWriter(file);
		writer.write(xml);
		writer.close();
		
	}
		
	private static void saveContactsToCsvFile(List<ContactData> contacts, File file) throws IOException {
		FileWriter writer = new FileWriter(file);
		for (ContactData contact : contacts) {
			writer.write(contact.getContactFirstname() +","+ contact.getContactLastname() +","+ contact.getContactFirstaddr() +
					","+ contact.getContactHomephone() +","+ contact.getContactMobile() +
					","+ contact.getContactWorkphone() +","+ contact.getContactFirstemail() +
					","+ contact.getGroupHeader() +","+ contact.getContactBday() +","+ contact.getContactBmonth() +
					","+ contact.getContactByear() +","+ contact.getContactGroup() +","+
					contact.getContactSecondaddr() + ","+ contact.getContactSecondphone() + ",!" + "\n");
		}
		writer.close();		
	}
	
	public List<ContactData> loadContactsToCsvFile(File file) throws IOException {
		List<ContactData> list = new ArrayList<ContactData>();
		FileReader reader = new FileReader(file);
		BufferedReader bufferedReader = new BufferedReader(reader);
		String line = bufferedReader.readLine();
		while (line != null) {
			String[] part = line.split(",");
			ContactData contact = new ContactData()
				.withFirstName(part[0])
				.withLastName(part[1])
				.withFirstAddress(part[2])
				.withHomePhone(part[3])
				.withMobilePhone(part[4])
				.withWorkPhone(part[5])
				.withFirstEmail(part[6])
				.withSecondEmail(part[7])
				.withBDay(part[8])
				.withBMonth(part[9])
				.withBYear(part[10])
				.withGroupLink(part[11])
				.withSecondAddress(part[12])
				.withSecondPhone(part[13]);
			list.add(contact);
			line = bufferedReader.readLine();
		}
		bufferedReader.close();	
		return list;
	}
	
	public  List<ContactData> loadContactsToXmlFile(File file) throws IOException {
		XStream xstream = new XStream();
		xstream.alias("contacts", ContactData.class);
		return (List<ContactData>) xstream.fromXML(file);
}
	
//----------------------------------------------------------------------------------
	
	/*public static String randomGroup() {
		List<WebElement> groupLink = driver.findElements(By.xpath("//select[@name='new_group']"));
		String randomGroups = "";
		if(groupLink.size() != 0){
			Random rnd = new Random();
			SortedListOf<String>  groupsList = getGroupListForContact();
			String[] array = groupsList.toArray(new String[groupsList.size()]);
			int r = rnd.nextInt(array.length);
			randomGroups = array[r];			
		}
		return randomGroups;
	}
	
	public static SortedListOf<String> cashedGroupsForContacts;
	
	public static SortedListOf<String> getGroupListForContact(){  
		if (cashedGroupsForContacts == null) {
			rebuildCachedGroupsForContacts();
		}
		return cashedGroupsForContacts;
	}		
	
    public static void rebuildCachedGroupsForContacts() {			
        	SortedListOf<String> cashedGroupsForContacts = new SortedListOf<String>();
        	appManager.getNaviHelper().openMainPage();
            List<WebElement> allGroupsOptions = driver.findElements(By.xpath("//select[@name='new_group']/option"));
            int optionCount = driver.findElements(By.xpath("//select[@name='new_group']/option")).size();
            for (int j = 1; j <= optionCount; j++) {
                  for(WebElement element : allGroupsOptions){
                  String      dropDown = element.getText();
                  cashedGroupsForContacts.add(dropDown);
                  }                      
            }
	}    */
	
	
	
	public  String generateRandomString(){	
		Random rnd = new Random();		
		char[] chars = new char[]{'+','&','?','-','/','=','_','(',')'};
		//char c = (char)(rnd.nextInt(128-32))+32 ;
		int r = rnd.nextInt(chars.length);
		char randomChar = chars[r];
				
		if (rnd.nextInt(3) == 0) {
			return "";
		} else {
			return "test " + rnd.nextInt() + " " + randomChar ;			
		}
	}
	
	public  String generateRandomMonth(){
		Random rnd = new Random();
		
		String[] months = new String[]{"January","February","March","April","May","June","July","August",
				"September","October","November","December"};
		int r = rnd.nextInt(months.length);
		String randomMonth = months[r];
		
		if (rnd.nextInt(3) == 0) {
			return "-";
		} else {
			return randomMonth ;			
		}		
	}	
	
	public  String generateRandomDay(){
		Random rnd = new Random();
		
		String[] days = new String[]{"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20",
				"21","22","23","24","25","26","27","28","29","30","31"};
		int r = rnd.nextInt(days.length);
		String randomDay = days[r];
		
		if (rnd.nextInt(3) == 0) {
			return "-";
		} else {
			return randomDay ;			
		}		
	}	
	
	public  String generateRandomYear(){
		Random rnd = new Random();
		int r = (int)(Math.random() * 2013)+1939;
		String randomYear = String.valueOf(r);
		
		if (rnd.nextInt(3) == 0) {
			return "";
		} else {
			return randomYear;			
		}
	}




}
